package com.shop.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.shop.Redis.CollectionKey;
import com.shop.Redis.RedisService;
import com.shop.dao.GoodsCollectionMapper;
import com.shop.pojo.*;
import com.shop.result.JsonResult;
import com.shop.service.GoodsCollectionService;
import com.shop.service.LoginService;
import com.shop.util.BaseUtil;
import net.sf.json.JSONArray;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

@Service
public class GoodsCollectionServiceImpl implements GoodsCollectionService {
    @Autowired
    private GoodsCollectionMapper goodsCollectionMapper;
    @Autowired
    private LoginService loginService;
    @Autowired
    private MongoTemplate mongoTemplate;

    /*定义集合名称*/
    private static final String collectionName = "goodsCollection";

    /*商品收藏数据查询*/
    @Override
    public JsonResult getUserCollectionByCondition(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String data = request.getParameter("data");
        String token = request.getParameter("token");
        User user = loginService.getUserByToken(token);
        if(user == null){
            return new JsonResult(false,"查询失败！该用户已失效，请重新登录");
        }

        Map<String,Object> params = StringUtils.isNotEmpty(data) ? BaseUtil.json2Map(data) : new HashMap<>();
        params.put("userId",user.getUserId());
        List<GoodsCollection> collections = new ArrayList<>();

        /*Mysql操作*/
//        collections =goodsCollectionMapper.queryUserCollectionByCondition(params);

        /*MongoDB操作*/
        Query query = new Query();
        query.fields().exclude("_id");
//        query.fields().include(collectionName);   //指定只返回的key对应value值

        for (Map.Entry<String,Object> map : params.entrySet()) {
            query.addCriteria(Criteria.where(map.getKey()).is(map.getValue()));
        }

        collections = mongoTemplate.find(query,GoodsCollection.class,collectionName);

        return new JsonResult(true,collections,collections.size());    //返回查询到的数据和数量
    }

    /*用户收藏商品*/
    @Override
    public JsonResult addUserCollection(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String data = request.getParameter("data");
        String token = request.getParameter("token");
        User user = loginService.getUserByToken(token);
        if(user == null){
            return new JsonResult(false,"商品收藏失败！该用户已失效，请重新登录");
        }

        data = BaseUtil.dataTranscoding(data);
        String json = BaseUtil.toJson(data);
        GoodsCollection goodsCollection = JSONObject.parseObject(json, GoodsCollection.class);
        goodsCollection.setUserId(user.getUserId());

        /*检测用户是否已收藏了该商品，避免重复收藏*/
        Map<String,Object> params = BaseUtil.json2Map(data);
        params.put("userId",user.getUserId());
        params.put("goodsId",goodsCollection.getGoodsId());

        /*Mysql操作*/
//        List<GoodsCollection> collections =goodsCollectionMapper.queryUserCollectionByCondition(params);
//        if(collections.size() > 0){
//            return new JsonResult(false,"商品收藏失败！该用户已收藏该商品，请勿重复收藏");
//        }
//
//        goodsCollection.setGcId(BaseUtil.getSID());
//        goodsCollection.setCreateTime(new Date());
//        goodsCollectionMapper.insert(goodsCollection);

        /*MongoDB操作*/
        Query query = new Query();
        query.fields().include(collectionName); //只显示购物车信息
        query.fields().exclude("_id");  //不显示MongoDB数据库中生成的id值
        for (Map.Entry<String,Object> map : params.entrySet()) {
            query.addCriteria(Criteria.where(map.getKey()).is(map.getValue()));
        }

        Map<String,Object> isCollection = mongoTemplate.findOne(query, Map.class, collectionName);   //查询MongoDB中单条的购物车商品数据
        if (isCollection == null || isCollection.size() == 0){
            goodsCollection.setGcId(BaseUtil.getSID());
            goodsCollection.setCreateTime(new Date());

            mongoTemplate.insert(goodsCollection,"goodsCollection");
            return new JsonResult(true,"商品收藏成功！");
        }

        return new JsonResult(false,"商品收藏失败！用户已收藏该商品，请勿重复收藏。");
    }

    /*用户取消商品收藏*/
    @Override
    public JsonResult deleteUserCollection(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String gcId = request.getParameter("gcId");
        if(StringUtils.isNotEmpty(gcId)){
            /*Mysql操作*/
//            goodsCollectionMapper.deleteByPrimaryKey(gcId);

            /*MongoDB操作*/
            Query query = new Query();
            query.addCriteria(Criteria.where("gcId").is(gcId));

            GoodsCollection goodsCollection = mongoTemplate.findOne(query,GoodsCollection.class);  //查询MongoDB数据中的单条数据
            if (goodsCollection != null){    //当查询出来的数据不为空时，方可执行remove方法
                mongoTemplate.remove(query, GoodsCollection.class);
            }
        }

        return new JsonResult(true,"商品取消收藏成功！");
    }

}
